<script setup>
import { Edit, Delete, Search, Shop } from '@element-plus/icons-vue'
import { ref, computed, onMounted, reactive } from 'vue'
import {
    sellerGetCategoryAPI,
    sellerGetGoodsAPI,
    createGoodsAPI,
    stateChangeAPI,
    deleteGoodsAPI,
    getDetailGoodsAPI,
    UpdateGoodsAPI
} from '@/apis/seller'
import avatar from '@/assets/images/300.png'
import { useSellerStore } from '@/stores/sellerStore'
const sellerStore = useSellerStore()
// -------------------------------------------分类------------------------------------------------------//
//商品分类数据模型
const category = ref([])
//获取分类数据
const getCategory = async () => {
    const res = await sellerGetCategoryAPI()
    category.value = res.data
}
onMounted(() => getCategory())

// 计算二级选项
const subCategoryOptions = computed(() => {
    const parent = category.value.find(item => item.id === categoryId.value)
    return parent?.children || [] // 返回子选项或空数组 // 返回子选项或空数组
})
const addSubCategoryOptions = computed(() => {
    const parent = category.value.find(item => item.id === addCategoryId.value)
    return parent?.children || [] // 返回子选项或空数组 // 返回子选项或空数组
})

// 清空二级选项值（当一级选项变化时）
const handleCategoryIdChange = () => {
    subCategoryId.value = ''
}
const addHandleCategoryIdChange = () => {
    addSubCategoryId.value = ''
}
//-------------------------------------------添加商品------------------------------------------//
// 添加商品
// 表单数据
const addGoodsForm = ref({
    goodsName: '',
    content: '',
    price: 0,
    goodsNumber: 1,
    shippingFee: 0
})
const isAdd = ref(false)//添加商品弹框是否显示
const addCategoryId = ref('')
const addSubCategoryId = ref('')
// 图片相关
const mainImgUpload = ref()//主图绑定的ref对象
const subImgUpload = ref()//副图绑定的ref对象
const mainImgUrl = ref('')//接受返回的主要图片url
const subImgUrls = ref([])
const fileList = ref([])
// 上传处理
const handleUpload = async () => {
    try {
        if (!validateForm()) return
        // 提交商品数据
        await submitGoodsData()
        ElMessage.success('商品添加成功')
    } catch (error) {
        ElMessage.error(`操作失败: ${error.message}`)
    }
}
const handleRemove = (file) => {
    // 确保文件已上传成功（包含 response 数据）
    if (file.response && file.response.data) {
        // 查找要删除的 URL 索引
        const index = subImgUrls.value.findIndex(url => url === file.response.data)
        // 如果找到则移除
        if (index !== -1) {
            subImgUrls.value.splice(index, 1)
        }
    }
}
//主副图片上传回调
const mainImgSuccess = (result) => {
    mainImgUrl.value = result.data
}
const subImgSuccess = (result) => {
    subImgUrls.value.push(result.data)
}
// 提交商品数据
const submitGoodsData = async () => {
    let postData = {
        ...addGoodsForm.value,
        category: {
            main: addCategoryId.value,
            sub: addSubCategoryId.value
        },
        images: {
            main: mainImgUrl.value,
            sub: subImgUrls.value
        }
    }
    await createGoodsAPI(postData)
    isAdd.value = false;
}
// 表单验证
const validateForm = () => {
    if (!addGoodsForm.value.goodsName) {
        ElMessage.warning('请输入商品名称')
        return false
    }
    if (!addCategoryId.value || !addSubCategoryId.value) {
        ElMessage.warning('请选择完整分类')
        return false
    }
    if (!mainImgUrl.value) {
        ElMessage.warning('请上传主图')
        return false
    }
    return true
}
//-------------------------------------------查询商品------------------------------------------//
//商品列表数据模型
onMounted(() => getGoodsList())

const categoryId = ref('')//搜索时的分类id
const subCategoryId = ref('')
const state = ref('')//搜索时的发布状态
const searchName = ref('')//搜索时的搜索名字
const page = ref(1)//当前页//分页条数据模型
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数


const goodsList = ref([])
const getGoodsList = async () => {
    //搜索参数
    let searchParams = ref({
        categoryId: categoryId.value,
        subCategoryId: subCategoryId.value,
        state: state.value,
        searchName: searchName.value,
        page: page.value,
        pageSize: pageSize.value
    })
    let res = await sellerGetGoodsAPI(searchParams.value)
    total.value = res.data.data.counts
    goodsList.value = res.data.data.items
}

//清除搜索信息
const clearSearchInfo = () => {
    categoryId.value = ''
    subCategoryId.value = ''
    state.value = ''
    searchName.value = ''
}


//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getGoodsList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    page.value = num
    getGoodsList()
}

// 创建格式化函数
const formatPayState = (payState) => {
    const stateMap = {
        1: '售卖中',
        0: '未上架'
    }
    return stateMap[payState]
}
//-------------------------------------------编辑商品------------------------------------------//
const stateChange = async (state, goodsId) => {
    const res = await stateChangeAPI(state, goodsId)
    getGoodsList()
}

const deleteGoods = async (goodsId) => {
    await deleteGoodsAPI(goodsId)
    getGoodsList()
}



const isUpdate = ref(false)
const updateGoodsForm = ref({
    goodsImg: '',
    goodsName: '',
    content: '',
    price: '',
    goodsNumber: '',
    shippingFee: '',
    updateCategoryId: '',
    updateSubCategoryId: ''
})
const getDetailGoods = async (goodsId) => {
    const res = await getDetailGoodsAPI(goodsId)
    // console.log('查到的商品信息是：');
    // console.log(res);
    updateGoodsForm.value = res.data
    updateGoodsForm.value.updateCategoryId = res.data.parentCategoryId
    updateGoodsForm.value.updateSubCategoryId = res.data.categoryId
    isUpdate.value = true
}
//修改主图片上传回调
const updateGoodsImgSuccess = (result) => {
    updateGoodsForm.value.goodsImg = result.data
}
// 计算二级分类选项
const updateSubCategoryOptions = computed(() => {
    const parent = category.value.find(item => item.id === updateGoodsForm.value.updateCategoryId)
    return parent?.children || [] // 返回子选项或空数组 // 返回子选项或空数组
})
// 清空二级选项值（当一级选项变化时）
const updateHandleCategoryIdChange = () => {
    updateGoodsForm.value.updateSubCategoryId = ''
}

//开始修改商品信息
const updateGoods = async () => {
    if (!validateUpdateForm()) return
    let postData = ({
        id:updateGoodsForm.value.id,
        goodsImg: updateGoodsForm.value.goodsImg,
        goodsName: updateGoodsForm.value.goodsName,
        content: updateGoodsForm.value.content,
        price: updateGoodsForm.value.price,
        goodsNumber: updateGoodsForm.value.goodsNumber,
        shippingFee: updateGoodsForm.value.shippingFee,
        categoryId: updateGoodsForm.value.updateSubCategoryId
    })
    let res = await UpdateGoodsAPI(postData)
    ElMessage.success(res.message ? res.message : '修改成功')
    getGoodsList()
    isUpdate.value = false;
}

// 表单验证
const validateUpdateForm = () => {
    if (!updateGoodsForm.value.goodsName) {
        ElMessage.warning('请输入商品名称')
        return false
    }
    if (!updateGoodsForm.value.updateCategoryId || !updateGoodsForm.value.updateSubCategoryId) {
        ElMessage.warning('请选择完整分类')
        return false
    }
    return true
}


</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>商品管理</span>
                <div class="extra">
                    <el-button type="primary" @click="isAdd = true">添加商品</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <!-- 一级选择 -->
        <el-form inline>
            <el-form-item label="选择分类：">
                <el-select v-model="categoryId" placeholder="请选择一级分类" style="width: 200px;"
                    @change="handleCategoryIdChange">
                    <el-option v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
                </el-select>
                <!-- 二级选择 -->
                <el-select v-model="subCategoryId" placeholder="请选择二级分类" style="width: 200px;">
                    <!-- 空状态提示 -->
                    <el-option v-if="!subCategoryOptions.length" :value="1" disabled>
                        <span class="empty-tip">
                            {{ categoryId ? '暂无子选项' : '请先选择上级选项' }}
                        </span>
                    </el-option>
                    <!-- 正常选项 -->
                    <el-option v-for="item in subCategoryOptions" :key="item.id" :label="item.categoryName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 200px;">
                    <el-option label="售卖中" value="1"></el-option>
                    <el-option label="待上架" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input :prefix-icon="Search" v-model="searchName" style="width: 200px" placeholder="请输入商品名" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getGoodsList()">搜索</el-button>
                <el-button @click="clearSearchInfo()">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 商品列表 -->
        <el-table :data="goodsList" style="width: 100%">
            <el-table-column label="图片" prop="goodsImg">
                <template #default="{ row }">
                    <img :src="row.goodsImg" style="width: 60px; height: 60px; object-fit: cover;">
                </template>
            </el-table-column>
            <el-table-column label="商品名" prop="goodsName" width="150"></el-table-column>
            <el-table-column label="分类" prop="categoryName"></el-table-column>
            <el-table-column label="价格" prop="price"></el-table-column>
            <el-table-column label="库存" prop="goodsNumber"></el-table-column>
            <el-table-column label="人气" prop="popularity"></el-table-column>
            <el-table-column label="评论数" prop="commentNumber"></el-table-column>
            <el-table-column label="运费" prop="shippingFee"> </el-table-column>
            <el-table-column label="状态" prop="state">
                <template #default="{ row }">
                    <span>{{ formatPayState(row.state) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button v-if="row.state === 0" class="iconfont icon-shangjia" circle plain type="success"
                        @click="stateChange(1, row.id)"></el-button>
                    <el-button v-else class="iconfont icon-xiajia" circle plain type="info"
                        @click="stateChange(0, row.id)"></el-button>
                    <el-button :icon="Edit" circle plain type="primary" @click="getDetailGoods(row.id)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteGoods(row.id)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    </el-card>

    <!-- 添加商品弹出页 -->
    <el-drawer v-model="isAdd" title="添加商品" :before-close="handleClose" direction="rtl" size="30%">
        <el-form :model="addGoodsForm" label-width="100px">
            <!-- 主图上传 -->
            <el-form-item label="商品主图" required>
                <el-upload ref="mainImgUpload" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                    action="/api/upload" name="file" :headers="{ 'Authorization': sellerStore.sellerInfo.data.token }"
                    :on-success="mainImgSuccess">
                    <img v-if="mainImgUrl" :src="mainImgUrl" class="avatar" width="200" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <!-- 副图上传 -->
            <el-form-item label="商品副图">
                <el-upload ref="subImgUpload" v-model:file-list="fileList" action="/api/upload" list-type="picture-card"
                    :multiple="true" :limit="5" accept="image/*" name="file"
                    :headers="{ Authorization: sellerStore.sellerInfo.data.token }" :on-success="subImgSuccess"
                    :auto-upload="true" :on-remove="handleRemove">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #tip>
                        <div class="el-upload__tip">最多上传5张副图，每张不超过5MB</div>
                    </template>
                </el-upload>
            </el-form-item>
            <!-- 其他表单项 -->
            <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="addGoodsForm.goodsName" autocomplete="off" width="150" />
            </el-form-item>
            <el-form-item label="内容" :label-width="formLabelWidth">
                <el-input v-model="addGoodsForm.content" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请描述一下你的商品" />
            </el-form-item>
            <el-form-item label="分类">
                <el-select v-model="addCategoryId" placeholder="请选择一级分类" @change="addHandleCategoryIdChange">
                    <el-option v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
                </el-select>
                <el-select v-model="addSubCategoryId" placeholder="请选择二级分类">
                    <!-- 空状态提示 -->
                    <el-option v-if="!addSubCategoryOptions.length" :value="1" disabled>
                        <span class="empty-tip">
                            {{ categoryId ? '暂无子选项' : '请先选择上级选项' }}
                        </span>
                    </el-option>
                    <!-- 正常选项 -->
                    <el-option v-for="item in addSubCategoryOptions" :key="item.id" :label="item.categoryName"
                        :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input-number v-model="addGoodsForm.price" :min="0">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth">
                <el-input-number v-model="addGoodsForm.goodsNumber" :min="1">
                    <template #suffix>
                        <span>件</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="运费" :label-width="formLabelWidth">
                <el-input-number v-model="addGoodsForm.shippingFee" :min="0">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input-number>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" size="large" @click="handleUpload" :disabled="!mainImgUrl">
                    添加商品
                </el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
    <!-- 查询商品 -->
    <el-drawer v-model="isUpdate" title="商品信息" :before-close="handleClose" direction="rtl" size="30%">
        <el-form :model="updateGoodsForm" label-width="100px">
            <!-- 主图上传 -->
            <el-form-item label="商品主图" required>
                <el-upload ref="mainImgUpload" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                    action="/api/upload" name="file" :headers="{ 'Authorization': sellerStore.sellerInfo.data.token }"
                    :on-success="updateGoodsImgSuccess">
                    <img v-if="updateGoodsForm.goodsImg" :src="updateGoodsForm.goodsImg" class="avatar" width="200" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <!-- 其他表单项 -->
            <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="updateGoodsForm.goodsName" autocomplete="off" width="150" />
            </el-form-item>
            <el-form-item label="内容" :label-width="formLabelWidth">
                <el-input v-model="updateGoodsForm.content" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
                    placeholder="请描述一下你的商品" />
            </el-form-item>
            <el-form-item label="分类">
                <el-select v-model="updateGoodsForm.updateCategoryId" placeholder="请选择一级分类"
                    @change="updateHandleCategoryIdChange">
                    <el-option v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
                </el-select>
                <el-select v-model="updateGoodsForm.updateSubCategoryId" placeholder="请选择二级分类">
                    <el-option v-for="item in updateSubCategoryOptions" :key="item.id" :label="item.categoryName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input-number v-model="updateGoodsForm.price" :min="0">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth">
                <el-input-number v-model="updateGoodsForm.goodsNumber" :min="1">
                    <template #suffix>
                        <span>件</span>
                    </template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="运费" :label-width="formLabelWidth">
                <el-input-number v-model="updateGoodsForm.shippingFee" :min="0">
                    <template #suffix>
                        <span>RMB</span>
                    </template>
                </el-input-number>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" size="large" @click="updateGoods">
                    修改商品
                </el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 150px;
            height: 150px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 150px;
            height: 150px;
            text-align: center;
        }
    }
}
</style>